package com.kgdev.cweb.mbean.admin.archive;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import com.kgdev.cweb.beans.prod.impl.ClientBean;
import com.kgdev.cweb.beans.pub.impl.ClientRoleBean;
import com.kgdev.cweb.entities.prod.managed.Client;
import com.kgdev.cweb.entities.prod.owned.client.ClientIdentification;
import com.kgdev.cweb.entities.pub.ClientRole;

@ManagedBean
@SessionScoped
public class AdminArticleBean implements Serializable {

	private static final long serialVersionUID = 1L;

	@EJB
	ClientBean clientBean;
	@EJB
	ClientRoleBean clientRoleBean;

	private List<Client> clients;

	private String mode;

	private Set<String> roles;

	private Client client;

	public void addUser() {
		if (clientBean.find(client.getClientId()) != null) {
			FacesContext
					.getCurrentInstance()
					.addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_ERROR,
									"Email already exists",
									"Please use another email or use edit to modify existing user"));
			return;
		}
		buildClient();
		clientBean.add(client);
		client = null;
		initClientList();
		mode = null;
	}

	public void editUser() {
		buildClient();
		clientBean.edit(client);
		client = null;
		initClientList();
	}

	public Client getClient() {
		return client;
	}

	public List<Client> getClients() {
		return clients;
	}

	public String getMode() {
		return mode;
	}

	public Set<String> getRoles() {
		return roles;
	}

	public void init() {
		initClientList();
	}

	public void initAddUser() {
		mode = "add";
		client = new Client();
		client.setIdentification(new ClientIdentification());
	}

	public void initEditUser(String clientId) {
		client = clientBean.find(clientId);
		mode = "edit";
	}

	public void setClient(Client client) {
		this.client = client;
	}

	public void setClients(List<Client> clients) {
		this.clients = clients;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public void setRoles(Set<String> roles) {
		this.roles = roles;
	}

	private void buildClient() {
		client.getIdentification().setClient(client);
	}

	@PostConstruct
	private void initClientList() {
		client = new Client();
		client.setIdentification(new ClientIdentification());
		clients = clientBean.findAll();
	}

	@SuppressWarnings("unused")
	@PostConstruct
	private void initRoles() {
		List<ClientRole> clientRoles = clientRoleBean.findAll();
		roles = new HashSet<>();
		for (ClientRole clientRole : clientRoles)
			roles.add(clientRole.getValue());
	}

}